建立api
python manage.py startapp [appName]
新增user app 範例:
python manage.py startapp user
system/
manage.py
system/
__init__.py
settings.py #項目的設置/配置
urls.py #建置api
asgi.py
wsgi.py
#新增部分
user/
migrations/ #會自動創建 #紀錄DataBase Table結構操作紀錄
__init__.py
__init__.py
admin.py #會自動創建 #後臺管理
apps.py
models.py #會自動創建 #創建DataBase Table
tests.py
views.py #接受 http(request)並返回 http(response)
urls.py #自己創建 ##建置api
#約在文件33行
INSTALLED_APPS = [
'user.apps.UserConfig',
]
Request and response
接受 http(request)並返回 http(response)
from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
# Create your views here.
@csrf_exempt
def login(request):
if request.method == 'POST':
body = json.loads(request.body)
parameters = body['parameters']
print(body)
return HttpResponse(json.dumps(parameters))
print(request.method)
return HttpResponse('ok')
須自己新增
API建置
from django.urls import path
from . import views
urlpatterns = [
path('login', views.login),
]
API建置
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('user.urls')),
]
*Terminal
python manage.py runserver
http://127.0.0.1:8000/user/login
網頁會收到後端回應OK
後端會收到前端GET請求